var jclass = {
	initData() {
		this.loadFont();
		window.onresize = this.loadFont;

		this.data = {
			tableData: [],
			delTableData: [],
			tableParams: {
				page: 1,
				size: 15,
				assessType: 1 // 1 地区 2 平台 3 企业
			}
		}
		this.getTableList();
		// this.creatTable({data:{},total:0});
		this.init()
		this.bindEvent();
	},
	loadFont() {
		var widthScreen = $(window).width();
		var nowFont = widthScreen / 1920 * 15;
		var htmlFont = document.getElementsByTagName('html')[0];
		htmlFont.style.fontSize = nowFont + "px";
		htmlFont.style.lineHeight = nowFont + "px";
	},
	init() {
		this.tableRowsObj = [] //表格加序号对象
		this.tableRows = []

		this.scoreArr = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
	},
	bindEvent() {
		this.nodatafun()
		let that = this
		$("#jtab2 ul li").click(function() {
			let index = $(this).index();
			// console.log(index)
			that.data.tableParams.assessType = $(this).data("type")
			$(this).addClass("active").siblings("li").removeClass("active");
			that.data.tableData = []
			that.tableRowsObj = []
			that.tableRows = []
			that.getTableList();
		})

		$("#khx_dialog_submit").click(() => {
			let score = 0
			this.data.tableData.forEach(item => {
				score += Number(item.score)
			})
			if(score !== 100) {
				// alert("总分必须等于100")
				JPop.alert({ msg: '总分必须等于100' })
				return
			}
			if (this.isRepeat(this.data.tableData)) {
				JPop.alert({ msg: '不能有重复项' })
				return
			}
			this.data.tableData.forEach((item, index) => {
				item.accessNameCode = ''
				item.orderNum = index + 1
				if(item.id) {
					item.additionalRule = item.additionalRule.split('于')[1].split("%")[0].split('次')[0].split('分')[0]
					item.assessCodeName = ''
					jrequest.put("/api/assess-criterions", item).then(res => {
						if(res) {
							closeDialog()
						}
					})
				} else {
					jrequest.post("/api/assess-criterions", item).then(res => {
						if(res) {
							closeDialog()
						}
					})
				}
				if (this.data.delTableData && this.data.delTableData.length > 0) {
					let delids = ''
					this.data.delTableData.forEach(id => {
						delids += id + ','
					})
					jrequest.delete(`/api/assess-criterions/${delids.slice(0,delids.length-1)}`, {}).then(res => {})
				}
				
			})
		})
	},
	// 判断是否有重复
	isRepeat(arrobj) {
		let hash = {}
		for (let i in arrobj) {
			if (hash[arrobj[i].accessCode]) {
				return true
			} else {
				hash[arrobj[i].accessCode] = true
			}
		}
		return false
	},
	// 弹框-分值select
	initDilaogScoreSelect() {
		let itemArr = this.scoreArr.map(i => `${i}分`)
		let strhtml = ''
		itemArr.forEach((i, index) => {
			strhtml += `<option value=${this.scoreArr[index]}>${i}</option>`
		})
		return strhtml
	},
	// 弹框-附加规则select
	initDilaogFjgzSelect(sortNum) {
		sortNum = sortNum || 1
		let itemArr = []
		if (sortNum == 1) {
			itemArr = this.scoreArr.map(i => `低于${i}%不得分`)
		} else if(sortNum == 2) {
			itemArr = this.scoreArr.map(i => `高于${i}次不得分`)
		} else {
			itemArr = this.scoreArr.map(i => `高于${i}分钟不得分`)
		}
		
		let strhtml = ''
		itemArr.forEach((i, index) => {
			strhtml += `<option value=${this.scoreArr[index]}>${i}</option>`
		})
		return strhtml
	},
	initDialogRow() {
		let str = ''
		this.data.tableData.forEach(item => {
			str = `<li>
                    <div>${item.index}</div>
                    <div>
                        <select class="khx-select" id=khx_select_${item.index} onchange="khSelect(${item.index})"></select>
                    </div>
                    <div id=khx_select_text_${item.index}>${item.accessNameCode}</div>
                    <div>
                        <select class="fz-select" id=fz_select_${item.index} onchange="fzSelect(${item.index})"></select>
                    </div>
                    <div>
                        <select class="gz-select" id=gz_select_${item.index} onchange="gzSelect(${item.index})"></select>
                    </div>
                    <div>
                        <span class="dele-row" onclick="delRow(${item.index})">删除</span>    
                    </div>
                </li>`
			this.tableRowsObj.push({
				xh: item.index,
				str: str
			})
			this.tableRows.push(str)
		})
		$("#tableul").html(this.tableRows)
		jrequest.get("/api/Dict/listDict", {jhiType: 'assess_criterion',type:this.data.tableParams.assessType}).then(res => {
			let strhtml = ''
			res.data.forEach(item => {
				strhtml += `<option value=${item.code}>${item.jhiValue}</option>`
			})
			$(".khx-select").html(strhtml)
			$(".fz-select").html(this.initDilaogScoreSelect())
			// $(".gz-select").html(this.initDilaogFjgzSelect())
			this.data.tableData.forEach(ele => {
				$(`#khx_select_${ele.index}`).find(`option[value=${ele.accessCode}]`).attr("selected", true)
				// let rule = ele.additionalRule.split('于')[1].split("%")[0]
				// $(`#gz_select_${ele.index}`).find(`option[value=${rule}]`).attr("selected", true)
				$(`#fz_select_${ele.index}`).find(`option[value=${ele.score}]`).attr("selected", true)

				let sortNum = 1
				if (ele.assessCodeName.indexOf('时长') !== -1) {
					sortNum = 3
				} else if(ele.assessCodeName.indexOf('次') !== -1) {
					sortNum = 2
				}
				$(`#gz_select_${ele.index}`).html(this.initDilaogFjgzSelect(sortNum))
				let rule = ele.additionalRule.split('于')[1].split("%")[0]
				$(`#gz_select_${ele.index}`).find(`option[value=${rule}]`).attr("selected", true)
			})
		})
	},
	addRow(index) {
		let str = `<li>
                        <div>${index}</div>
                        <div>
                            <select class="khx-select" id=khx_select_${index} onchange="khSelect(${index})"></select>
                        </div>
                        <div id=khx_select_text_${index}>车辆入网率*分值</div>
                        <div>
                            <select class="fz-select" id=fz_select_${index} onchange="fzSelect(${index})"></select>
                        </div>
                        <div>
                            <select class="gz-select" id=gz_select_${index} onchange="gzSelect(${index})"></select>
                        </div>
                        <div>
                            <span class="dele-row" onclick="delRow(${index})">删除</span>    
                        </div>
                    </li>`
		this.tableRowsObj.push({
			xh: index,
			str: str
		})
		this.tableRows.push(str)
		this.data.tableData.push({
			assessType: this.data.tableParams.assessType,
			assessName: 1,
			additionalRule: 5,
			score: 5,
			ruleType: 2,
			accessCode: 1
		})
		$("#tableul").append(str)
		jrequest.get("/api/Dict/listDict", {jhiType: 'assess_criterion',type:this.data.tableParams.assessType}).then(res => {
			let strhtml = ''
			res.data.forEach(item => {
				strhtml += `<option value=${item.code}>${item.jhiValue}</option>`
			})
			$(`#khx_select_${index}`).html(strhtml)
			$(`#fz_select_${index}`).html(this.initDilaogScoreSelect())
			$(`#gz_select_${index}`).html(this.initDilaogFjgzSelect())
		})
	},
	delRow(index) {
		let obj = this.data.tableData[index - 1]
		// if(obj.id) {
		// 	jrequest.delete(`/api/assess-criterions/${obj.id}`, {}).then(res => {
		// 		if(res) {
		// 			this.data.tableData.splice(index - 1, 1)
		// 			$("#tableul>li").filter(function(num) {
		// 				return num === index - 1
		// 			}).remove()
		// 		}
		// 	})
		// } else {
		// 	this.data.tableData.splice(index - 1, 1)
		// 	$("#tableul>li").filter(function(num) {
		// 		return num === index - 1
		// 	}).remove()
		// }
		this.data.delTableData.push(obj.id)
		this.data.tableData.splice(index - 1, 1)
		$("#tableul>li").filter(function(num) {
			return num === index - 1
		}).remove()
		this.nodatafun()
	},
	nodatafun() {
		if(this.data.tableData.length === 0) {
			$("#tableul").html(`<li><p class="no-data">暂无数据</p></li>`)
		}
	},
	getTableList() {
		jrequest.get("/api/assess-criterions", this.data.tableParams).then(res => {
			if(res.data && res.data.length) {
				res.data.forEach((item, index) => {
					item.index = index + 1
					if (item.assessName == 1) {
						item.additionalRule = `低于${item.additionalRule}%不得分`
					} else if(item.assessName == 2) {
						item.additionalRule = `高于${item.additionalRule}次不得分`
					} else {
						item.additionalRule = `高于${item.additionalRule}分钟不得分`
					}
					
					item.accessNameCode = `${item.assessCodeName}*分值`
				})
			} else {
				this.nodatafun()
			}
			this.data.tableData = res.data
			$("#jtable_nationainfo").bootstrapTable('destroy');
            this.creatTable(res)
			// $("#jtable_nationainfo").bootstrapTable('load', res.data);

		})
	},
	creatTable: function(res) {
		var self = this;
		var columnsOne = [
			{
                field: 'no',
                title: '序号',
                align: 'center',
                formatter: function(value, row, index) {
                    return index + 1;
                }
            },
			{
				field: 'assessCodeName',
				title: '考核项'
			},
			{
				field: 'accessNameCode',
				title: '计分标准'
			},
			{
				field: 'score',
				title: '分值',
			},
			{
				field: 'additionalRule',
				title: '附加规则',
			}

		];
		self.tableEvent("jtable_nationainfo", res.data, columnsOne, true, res.total);
	},
	tableEvent: function(id, data, columns, paginationShow, total) {
		let that = this
		$('#' + id).bootstrapTable({
			method: 'get',
			cache: false,
			height: 320,
			pagination: paginationShow,
			pageSize: that.data.tableParams.size,
			pageNumber: that.data.tableParams.page,
			striped: true,
			columns: columns,
			sidePagination: 'server', // client or server
			totalRows: total,
			data: data,
			onPageChange: function(size, number) {
				// console.log(number)
				that.data.tableParams.page = number
				that.data.tableParams.size = size
				that.getTableList()
			},
			formatNoMatches: function() {
				return '暂无数据';
			}
		});
	},
}
$(function() {
	jclass.initData()

})

function editDialog() {
	$("#gzDialog").show()
	jclass.initDialogRow()
}

function addRow() {
	// jclass.addRow(jclass.tableRows.length + 1)
	jclass.addRow(jclass.data.tableData.length+1)
}

function delRow(index) {
	jclass.delRow(index)
}

function closeDialog() {
	jclass.data.tableData = []
	jclass.tableRowsObj = []
	jclass.tableRows = []
	jclass.getTableList()
	$("#gzDialog").hide()
}
// 弹框 考核项选择
function khSelect(index) {
	let text = $(`#khx_select_${index} option:selected`).text()
	let val = $(`#khx_select_${index} option:selected`).val()
	$(`#khx_select_text_${index}`).text(`${text}*分值`)
	jclass.data.tableData[index - 1].accessCode = val
	let sortNum = 1
	if (text.indexOf('时长') !== -1) {
		sortNum = 3
	} else if(text.indexOf('次') !== -1) {
		sortNum = 2
	}
	jclass.data.tableData[index - 1].assessName = sortNum
	jclass.data.tableData[index - 1].accessNameCode = text

	// sortNum 1百分比 2次数 3分钟
	$(`#gz_select_${index}`).html(jclass.initDilaogFjgzSelect(sortNum))
	
}

function fzSelect(index) {
	let val = $(`#fz_select_${index} option:selected`).val()
	jclass.data.tableData[index - 1].score = val
}

function gzSelect(index) {
	let val = $(`#gz_select_${index} option:selected`).val()
	jclass.data.tableData[index - 1].additionalRule = val
}